import matplotlib.pyplot as plt
import matplotlib.dates as mpld
import numpy as np
import datetime
import networkx as nx
from collections import OrderedDict
#import community
import common
import calendar

my_colors = ['#1f77b4', #blue             
             '#ff7f0e', #orange             
             '#2ca02c', #green             
             '#d62728', #red             
             '#9467bd', #purple
             '#8c564b', #brown
             '#e377c2', #pink
             '#7f7f7f', #gray
             '#bcbd22', #yellow-green
             '#17becf', #cyan
             '#aec7e8', #light blue
             '#ffbb78', #light orange
             '#98df8a', #light green
             '#ff9896', #light red
             '#c5b0d5', #light purple
             '#c49c94', #light brown
             '#f7b6d2', #light pink
             '#c7c7c7', #light gray
             '#dbdb8d', #light yellow-green
             '#9edae5'] #light cyan
             

OUTPUT_FOLDER = "Output"   

mode_set = {'walk'  : 0, #blue
            'bike'  : 1, #orange
            'stand' : 2, #green
            'run'   : 3, #red
            'train' : 4, #purple
            'bus'   : 5} #brown

def get_ax_size(fig, ax):
    bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
    width, height = bbox.width, bbox.height
    width *= fig.dpi
    height *= fig.dpi
    return width, height
    
def plot_figure_1(data, delta, class_data, from_date, end_date, figname, figsize, ground_truth=False, jaccard_data={}, node_colour={}, y_ticks=False):
    jaccard_color = my_colors[1]
    ground_truth_color = '0.75'
    
    # CREATE FIGURE    
    if len(jaccard_data) > 0:
        fig, axarr = plt.subplots(2, sharex=True, figsize=figsize)
        ax = axarr[0] 
    else:
        fig, axarr = plt.subplots(1, figsize=figsize)
        ax = axarr
     
    # PLOT ROUTER DATA
    #TODO: optimize
     
    counter = 0
    for key in data.keys():
        sorted_data = sorted(data[key], reverse = True, key=lambda x: x[0])
        filtered_data = []
        for item in sorted_data:
            if item[0] >= from_date and item[0] <= end_date:
                filtered_data.append(item)
       
        if len(node_colour) > 0:
            for item in sorted_data:
                if node_colour.has_key(key):
                    ax.plot([item[0], item[0] + datetime.timedelta(minutes = delta) + datetime.timedelta(seconds = 1)], [counter, counter], node_colour[key], linewidth=1)
        else:
            for item in sorted_data:
                ax.plot([item[0], item[0] + datetime.timedelta(minutes = delta) + datetime.timedelta(seconds = 1)], [counter, counter], my_colors[0], linewidth=1)
        counter = counter + 1
        
    # TITLE
#    ax.set_title("Presence of routers over time")
    
    # XAXIS
    plt.xlabel("Time")
    ax.xaxis.set_major_formatter(mpld.DateFormatter('%d/%m/%y %H:%M'))
    plt.tick_params(axis='x', which='major', labelsize=6)
    plt.xlim(from_date, end_date) 
    plt.xticks(prepare_x_ticks(from_date, end_date, 24), rotation=90)
    
    # YAXIS
    ax.set_ylabel('Access points')
    ax.set_ylim([-1, len(data.keys()) + 1])
    
    if y_ticks:
        plt.yticks(xrange(0, len(data.keys())), [item[1] for item in data.keys()])
        plt.tick_params(axis='y', which='major', labelsize=6)
    else:
        plt.setp(ax.get_yticklabels(), visible=False)
        plt.tick_params(axis='y', which='both', bottom='off', top='off', labelbottom='off')
        ax.set_yticks([])
        
    # PLOT GROUND TRUTH ON THE MAIN DIAGRAM    
    class_data = prepare_class_data(class_data, from_date, end_date)
    if ground_truth:
        for idx in xrange(0, len(class_data) - 1, 2):
            if (class_data.keys()[idx] >= from_date and class_data.keys()[idx] <= end_date) or (class_data.keys()[idx + 1] <= end_date and class_data.keys()[idx + 1] >= from_date):
                ax.axvspan(class_data.keys()[idx], class_data.keys()[idx + 1], color=ground_truth_color, alpha=0.5)
            
    # PLOT GROUND TRUTH ON JACCARD DIAGRAM
    if len(jaccard_data) > 0:
        ax = axarr[1]
        for idx in xrange(0, len(class_data) - 1, 2):
            ax.axvspan(class_data.keys()[idx], class_data.keys()[idx + 1], color=ground_truth_color, alpha=0.5)
        ax.set_ylim([0, 1])
        
    # PLOT JACCARD DIAGRAM
    if len(jaccard_data) > 0:
        jac_handle, = ax.plot(jaccard_data.keys(), jaccard_data.values(), color=jaccard_color)
        ax.set_ylabel('Jaccard index')
        plt.ylim(0, 1.05)
        
        
    # SAVE
    plt.savefig(OUTPUT_FOLDER + "//" + figname, bbox_inches='tight')       
    plt.close(fig)
    
def plot_jaccard(jaccard_data, class_data, delta, from_date, end_date, figname, ground_truth=False):
    fig = plt.figure()
    ax = plt.gca() 
    plt.gca().xaxis.set_major_formatter(mpld.DateFormatter('%d/%m/%y %H:%M'))
    plt.title("Jaccard index over time computed from " + str(delta) + " min time bins")
    
    ax.plot(jaccard_data.keys(), jaccard_data.values(), 'g')
    
    if ground_truth:
        for item in class_data.keys():
            ax.plot([item, item], [0, 1], 'r')
            
    plt.xlim(from_date, end_date)
    prepare_x_ticks(from_date, end_date, 24)
    plt.tick_params(axis='y', which='major', labelsize=8)
    plt.tick_params(axis='x', which='major', labelsize=8)
    plt.xlabel("Time")
    plt.ylabel("Jaccard index")
    plt.savefig(OUTPUT_FOLDER + "//" + figname, bbox_inches='tight')       
    plt.close(fig)
    
def plot_jaccard_diff(jaccard_data, class_data, delta, from_date, end_date, figname, ground_truth=False):
    fig = plt.figure()
    ax = plt.gca() 
    plt.gca().xaxis.set_major_formatter(mpld.DateFormatter('%d/%m/%y %H:%M'))
    plt.title("Jaccard index difference over time computed from " + str(delta) + " min time bins")
    
    ax.plot(jaccard_data.keys(), jaccard_data.values(), 'g')
    
    if ground_truth:
        for item in class_data.keys():
            ax.plot([item, item], [-1, 1], 'r')
            
    plt.xlim(from_date, end_date)
    plt.ylim(-1,1)
    plt.xticks(prepare_x_ticks(from_date, end_date, 24), rotation=90)
    plt.tick_params(axis='y', which='major', labelsize=8)
    plt.tick_params(axis='x', which='major', labelsize=8)
    plt.xlabel("Time")
    plt.ylabel("Jaccard index difference")
    plt.savefig(OUTPUT_FOLDER + "//" + figname, bbox_inches='tight')       
    plt.close(fig)
    
def plot_router_network(data, figname, k_clique, min_width=0):
    wifi_data = common.convert_dict_to_date_router_list(data)
    G = nx.Graph()
#    for router in data.keys():
#        G.add_node(router)
    
    wifi_data_pairs = OrderedDict()
    for routers_set in wifi_data.values():
        for router_a in routers_set:
            for router_b in routers_set:
                if(router_a != router_b):
                    if(wifi_data_pairs.has_key((router_a, router_b))):
                        wifi_data_pairs[(router_a, router_b)] = wifi_data_pairs[(router_a, router_b)] + 1
                    elif wifi_data_pairs.has_key((router_b, router_a)):
                        wifi_data_pairs[(router_b, router_a)] = wifi_data_pairs[(router_b, router_a)] + 1
                    else:
                        wifi_data_pairs[(router_a, router_b)] = 1
     
    for single_date in wifi_data.keys():
        for router_a in wifi_data[single_date]:
            for router_b in wifi_data[single_date]:
                if(router_a != router_b):
                    if(wifi_data_pairs.has_key((router_a, router_b))):
                        w = wifi_data_pairs[(router_a, router_b)]
                    elif(wifi_data_pairs.has_key((router_b, router_a))):
                        w = wifi_data_pairs[(router_b, router_a)]
                    else:
                        w = 0
                    
                    if w > min_width:
                        G.add_edge(router_a, router_b, weight = w)
    
    node_size_list = []    
    for node in G.nodes():
        node_size_list.append(len(data[node]))
    
    fig = plt.figure(figsize=(16, 8))    
    pos = nx.spring_layout(G, scale = 2) 
    node_colour = {}
    
    G_out = nx.Graph()
    
    if k_clique > 0:            
        clique_list = list(nx.k_clique_communities(G, k_clique))
        for node in G.nodes():
            for idx in xrange(0, len(clique_list)):
                if node in clique_list[idx]:
                    node_colour[node] = my_colors[idx]
                    G_out.add_node(node, group=idx)
            if not node_colour.has_key(node):
                node_colour[node] = "#000000"
                G_out.add_node(node, group=-1)
            
        node_colour_list = []
        for node in G.nodes():          
            node_colour_list.append(node_colour[node])
            
        for idx in clique_list:
            nx.draw_networkx_nodes(G, pos, G.nodes(), node_color=node_colour_list, node_size = node_size_list)
            
    else: #louvain
        partition = community.best_partition(G)
        pos = nx.spring_layout(G)
        count = 0
        for com in set(partition.values()) :

            list_nodes = [nodes for nodes in partition.keys()
                                        if partition[nodes] == com]
            nx.draw_networkx_nodes(G, pos, list_nodes, node_size = node_size_list,
                                        node_color = my_colors[count])
            for node in list_nodes:
                node_colour[node] = my_colors[count]
            count = count + 1
          
    for edge in G.edges():
        G_out.add_edge(edge[0], edge[1])
        
    nx.write_gexf(G_out, 'undir.gefx')
    nx.draw_networkx_edges(G, pos, alpha = 0.4)
    plt.axis('off')
    plt.savefig(OUTPUT_FOLDER + "//" + figname, bbox_inches='tight')
    plt.show()
    plt.close(fig)        
    return node_colour
    
def plot_router_network_directed(data, ground_truth, filename):
    wifi_data = common.convert_dict_to_date_router_list(data)
#    gt_classes = {}
#    gt = ground_truth.keys()
#    stop_location_id = 0
#    for idx in xrange(0, len(gt) - 1):
#        if((ground_truth[gt[idx]], ground_truth[gt[idx + 1]]) == ('walk', 'stand')): # travel
#            gt_classes[(gt[idx], gt[idx + 1])] = -1
#        else: # stop location
#            gt_classes[(gt[idx], gt[idx + 1])] = 1
#            stop_location_id = stop_location_id + 1
#    
#    router_class = {}
#    for router in data.keys():
#        date_class = []
#        for s_date in data[router]:
#            for gt_class in gt_classes.keys():
#                if s_date[0] > gt_class[0] and s_date[0] <= gt_class[1]:
#                    date_class.append(gt_classes[gt_class])
#        if len(date_class) == 0:
#            router_class[router] = 1
#        else:
#            if most_common(date_class) == 4:
#                router_class[router] = 0
#            elif most_common(date_class) == 3:
#                router_class[router] = 1
#            else:
#                router_class[router] = most_common(date_class)
    G = nx.MultiDiGraph()
    
    for date_idx in xrange(0, len(wifi_data.keys()) - 1):
        curr_date = wifi_data.keys()[date_idx]
        next_date = wifi_data.keys()[date_idx + 1]
        # for curr_date add all routers
        
        for router in wifi_data[curr_date]:
            if(not G.has_node(router)):
                G.add_node(router, weight = 1, size = len(data[router]))
        
        #for next_date add the loops
        for router in wifi_data[next_date]:
            if(not G.has_node(router)):
                G.add_node(router, weight = 1, size = len(data[router]))
            for router_prev in wifi_data[curr_date]:
                if(not G.has_edge(router_prev, router)):
                    # add new edge with weight 1
                    G.add_edge(router_prev, router, weight = 1)
                else:
                    weight = G.get_edge_data(router_prev, router)[0]['weight']
                    G.remove_edge(router_prev, router)
                    G.add_edge(router_prev, router, weight = weight + 1)
                
    #edge_labels=dict([((u,v,),d['weight']) for u,v,d in G.edges(data=True)])
    nx.write_gexf(G, filename)
#    pos = nx.spring_layout(G)
#    fig = plt.figure()
#    ax = plt.gca()
#    nx.draw_networkx_nodes(G, pos, node_size = 5)
#        
#    nx.draw_networkx_edges(G, pos, alpha = 0.2, arrows = True)
#    #nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
#    #nx.draw_networkx_labels(G, pos)
#    plt.axis('off')
#    plt.show()
#    plt.savefig(figname) 
#    plt.close()

def plot_router_histogram(hist_data, bin_num):
    # Histogram of access points   
    fig = plt.figure()
    ax = plt.gca() 
    ax.hist(hist_data.values(), bins = bin_num)
     
    plt.title("Histogram of number of occurences of access points")
    plt.xlabel("Number of occurences")
    plt.ylabel("Number of access points")
    plt.savefig(OUTPUT_FOLDER + "//" + "ac_histogram.pdf", bbox_inches='tight')       
    plt.close(fig)

def plot_merging(data, class_data, main_router, to_remove, from_date, end_date, figname, figsize, ground_truth=False, jaccard_data={}, node_colour={}):
    step = 4
    node_size = 1
    fig = plt.figure(figsize=figsize)
    ax = plt.gca() 
    counter = 0
    for key in data.keys():
        sorted_data = sorted(data[key], reverse = True, key=lambda x: x[0])
        filtered_data = []
        for item in sorted_data:
            if item[0] >= from_date and item[0] <= end_date:
                filtered_data.append(item)
        ssid_name = np.ones(len(filtered_data)) * counter 
        
        for router in filtered_data:
            if key == main_router:
                curr_color = my_colors[0]
#                plt.plot([key[0], key[0] + datetime.timedelta(minutes = delta)], [counter, counter], curr_color)
            elif key in to_remove:
                curr_color = my_colors[2]
#                plt.plot([key[0], key[0] + datetime.timedelta(minutes = delta)], [counter, counter], curr_color)
            else:
                curr_color = my_colors[5]
#                plt.plot([key[0], key[0] + datetime.timedelta(minutes = delta)], [counter, counter], curr_color)
                   
        for item in filtered_data:
            plt.plot([item[0], item[0] + datetime.timedelta(minutes = delta)], [counter, counter], 'b')
        ax.scatter([i[0] for i in filtered_data], ssid_name, facecolor=curr_color, s = node_size, edgecolor= curr_color, lw = 0, label='Router presence')
        #print scatter_colors
        counter = counter + step    
    plt.gca().xaxis.set_major_formatter(mpld.DateFormatter('%d/%m/%y %H:%M'))
    plt.title("Presence of routers over time")
    plt.ylim(-1, len(data.keys()) * step + 1)
    
    if ground_truth:
        for item in class_data.keys():
            gt_handle, = ax.plot([item, item], [-1, ax.get_ylim()[0] + ax.get_ylim()[1]], 'r', label='Ground truth')
            
    ax.set_ylabel('Access points')
    plt.xlim(from_date, end_date)
    plt.xticks(prepare_x_ticks(from_date, end_date, 24), rotation=90)
    plt.tick_params(axis='x', which='major', labelsize=8)
    plt.xlabel("Time")
    
    if figsize == (8,12):
        plt.yticks(xrange(0, len(data.keys()) * step, step), data.keys())
    else:
        plt.tick_params(axis='y', which='both', bottom='off', top='off', labelbottom='off')
    plt.yticks(xrange(0, len(data.keys()) * step, step), data.keys())
    plt.tick_params(axis='y', which='major', labelsize=1)
    
    if len(jaccard_data.keys()) > 0:
        ax2 = ax.twinx()
        jac_handle, = ax2.plot(jaccard_data.keys(), jaccard_data.values(), 'g', label='Jaccard index')
        ax2.set_ylabel('Jaccard index')
#        circ1 = Line2D([0], [0], linestyle="none", marker="o", markersize=5, markerfacecolor="b")
#        circ2 = Line2D([], [], color='g', label='Jaccard index')
#        circ3 = Line2D([], [], color='r', label='Ground truth')
        plt.ylim(0, 1.05)
#        plt.legend((circ1, circ2, circ3), ("Router presence", "Jaccard index", "Ground truth"), numpoints=1, loc="best",prop={'size':7})
    
    plt.xlim(from_date, end_date)
    
    plt.savefig(OUTPUT_FOLDER + "//" + figname, bbox_inches='tight')       
    plt.close(fig)
    
divtdi = datetime.timedelta.__div__
def divtd(td1, td2):
    if isinstance(td2, (int, long)):
        return divtdi(td1, td2)
    us1 = td1.microseconds + 1000000 * (td1.seconds + 86400 * td1.days)
    us2 = td2.microseconds + 1000000 * (td2.seconds + 86400 * td2.days)
    return us1 / us2 # this does integer division, use float(us1) / us2 for fp division
    
def prepare_x_ticks(start_date, end_date, num):
    delta_date = (end_date - start_date)
    single_delta = divtd(delta_date, num)
    
    xtick_list = []
    curr_date = start_date
    if curr_date > end_date:
        temp_date = curr_date
        curr_date = end_date
        end_date = temp_date
        
    while curr_date <= end_date:
        xtick_list.append(curr_date)
        curr_date = curr_date + single_delta
    return xtick_list

def prepare_x_ticks_words(start_date, end_date, num):
    delta_mins = 10    
    time_delta = datetime.timedelta(minutes = delta_mins)    
    start_mins = start_date.minute #23
    start_mins_eq = int(start_mins / delta_mins) * delta_mins #20
    print start_mins_eq
    delta_start = delta_mins - (start_mins - start_mins_eq) #7
    
    x_tick_pos = []
    x_tick_lab = []    
    curr_date = start_date + datetime.timedelta(minutes = delta_mins - (start_mins - start_mins_eq))
    for idx in xrange(delta_start, num, delta_mins):
        x_tick_lab.append(curr_date.strftime('%d/%m/%y %H:%M'))
        x_tick_pos.append(idx)
        curr_date = curr_date + time_delta
    return [x_tick_pos, x_tick_lab]
    
def most_common(lst):
    return max(set(lst), key=lst.count)

def plot_figure_scatter(data, class_data, from_date, end_date, figname, figsize, ground_truth=False, jaccard_data={}, node_colour={}, y_ticks=False):
    jaccard_color = my_colors[3]
    ground_truth_color = '0.75'
    
    # CREATE FIGURE    
    if len(jaccard_data) > 0:
        fig, axarr = plt.subplots(2, sharex=True, figsize=figsize)
        ax = axarr[0] 
    else:
        fig, axarr = plt.subplots(1, figsize=figsize)
        ax = axarr
     
    # PLOT ROUTER DATA
    #TODO: optimize
     
    counter = 0
    for key in data.keys():
        sorted_data = sorted(data[key], reverse = True, key=lambda x: x[0])
        filtered_data = []
        for item in sorted_data:
            if item[0] >= from_date and item[0] <= end_date:
                filtered_data.append(item)
       
        if len(node_colour) > 0:
            ax.scatter([i[0] for i in filtered_data], [counter for i in filtered_data], facecolor=node_colour[key], s = 1.5, edgecolor= node_colour[key], lw = 0, marker='s')
#            for item in sorted_data:                
#                ax.plot([item[0], item[0] + datetime.timedelta(seconds = delta)], [counter, counter], node_colour[key])
        else:
            ax.scatter([i[0] for i in filtered_data], [counter for i in filtered_data], facecolor=my_colors[0], s = 1.5, edgecolor= my_colors[0], lw = 0, marker='s')
#            for item in sorted_data:

#                ax.plot([item[0], item[0] + datetime.timedelta(seconds = delta)], [counter, counter], my_colors[0])
        counter = counter + 1
        
    # TITLE
#    ax.set_title("Presence of routers over time")
    
    # XAXIS
    plt.xlabel("Time")
    ax.xaxis.set_major_formatter(mpld.DateFormatter('%d/%m/%y %H:%M'))
    plt.tick_params(axis='x', which='major', labelsize=6)
    plt.xlim(from_date, end_date) 
    plt.xticks(prepare_x_ticks(from_date, end_date, 24), rotation=90)
    
    # YAXIS
    ax.set_ylabel('Access points')
    ax.set_ylim([-1, len(data.keys()) + 1])
    
    if y_ticks:
        plt.yticks(xrange(0, len(data.keys())), [item[1] for item in data.keys()])
        plt.tick_params(axis='y', which='major', labelsize=6)
    else:
        plt.setp(ax.get_yticklabels(), visible=False)
        plt.tick_params(axis='y', which='both', bottom='off', top='off', labelbottom='off')
        plt.yticks([], [])
        
    class_data = prepare_class_data(class_data, from_date, end_date)
    print class_data
    # PLOT GROUND TRUTH ON THE MAIN DIAGRAM    
    if ground_truth:
        for idx in xrange(0, len(class_data) - 1, 2):
            if (class_data.keys()[idx] >= from_date and class_data.keys()[idx] <= end_date) or (class_data.keys()[idx + 1] <= end_date and class_data.keys()[idx + 1] >= from_date):
                plt.axvspan(class_data.keys()[idx], class_data.keys()[idx + 1], color=ground_truth_color, alpha=0.5)
            
    # PLOT GROUND TRUTH ON JACCARD DIAGRAM
    if len(jaccard_data) > 0:
        ax = axarr[1]
        for idx in xrange(0, len(class_data) - 1, 2):
            plt.axvspan(class_data.keys()[idx], class_data.keys()[idx + 1], color=ground_truth_color, alpha=0.5)
        ax.set_ylim([0, 1])
        
    # PLOT JACCARD DIAGRAM
    if len(jaccard_data) > 0:
        jac_handle, = ax.plot(jaccard_data.keys(), jaccard_data.values(), color=jaccard_color)
        ax.set_ylabel('Jaccard index')
        plt.ylim(0, 1.05)
        
    # SAVE
    plt.savefig(OUTPUT_FOLDER + "//" + figname, bbox_inches='tight')       
    plt.close(fig)
    
def prepare_class_data(class_data, from_date, end_date):
    new_class_data = OrderedDict()
    for item in class_data.keys():
        if item >= from_date and item <= end_date and class_data[item] != "start_data" and class_data[item] != "end_data":
            new_class_data[item] = class_data[item]
    print new_class_data
    return new_class_data
    
def plot_router_trans_matrix(data, class_data, class_data_detail, from_date, end_date, figname, figsize, ground_truth=False, speed_data={}, node_colour={}, y_ticks=False):
    speed_color = '#000000'
    [vd, router_names] = common.to_vector_data_removal(data, from_date, end_date)
    if len(vd) > 0:
        fig, axes = plt.subplots(ncols=2, sharex=True, figsize=figsize)
        plt.setp(axes.flat, adjustable='box-forced')
        if len(speed_data) > 0:
            tight = 0.95
            max_speed = max(speed_data.values())
            if max_speed == 0:
                mul = 0
            else:
                mul = len(vd) / max_speed * tight
            
            y_lims = [0, len(vd)]
            step = int(max_speed / 5.0)
            
            if max_speed > 5:
                ytick_lab = [str(item) for item in range(0, int(max_speed * 1.2), step)]
                ytick_pos = [item * mul for item in range(0, int(max_speed * 1.2), step)]
            else:
                step = max_speed / 5.0
                ytick_lab = [str(round(item, 2)) for item in common.drange(0, max_speed * 1.2, step)]
                ytick_pos = [round(item, 2) * mul for item in common.drange(0, max_speed * 1.2, step)]        
                
            axes[1].plot(xrange(len(speed_data)), [item * mul for item in speed_data.values()], c = speed_color, linewidth = 2)
            axes[1].set_aspect(1)
            axes[1].set_ylim(y_lims)
            axes[1].set_yticks(ytick_pos)
            axes[1].set_yticklabels(ytick_lab)
            axes[1].set_ylabel('Speed [km / h]')
        
        axes[0].set_ylabel('Access points')
        axes[0].imshow(vd, cmap=plt.cm.gray_r, interpolation='nearest') 
        axes[0].set_yticklabels([])
        
        tick_num = int((end_date - from_date).seconds / float(60))
        [xtick_pos, xtick_lab] = prepare_x_ticks_words(from_date, end_date, tick_num) 
        axes[0].set_xticks(xtick_pos)
        axes[0].set_xticklabels(xtick_lab, rotation=90)
        axes[1].set_xticks(xtick_pos)
        axes[1].set_xticklabels(xtick_lab, rotation=90)
        
        small_class_data_detail = OrderedDict()
        prev_date = None
        for idx in xrange(len(class_data_detail.keys())):
            curr_date = class_data_detail.keys()[idx]
            if curr_date >= from_date and curr_date <= end_date:
                if prev_date != None:
                    small_class_data_detail[prev_date] = class_data_detail[prev_date] 
                small_class_data_detail[curr_date] = class_data_detail[curr_date]           
            prev_date = curr_date
        
            
        for idx in xrange(len(small_class_data_detail.keys())):
            curr_date = small_class_data_detail.keys()[idx]
            if idx == len(small_class_data_detail.keys()) - 1:
                next_date = end_date
            else:
                next_date = small_class_data_detail.keys()[idx + 1]
                
            mode = small_class_data_detail[curr_date]
            for m in mode_set:
                if m in mode:
                    axes[1].axvspan(common.date_diff_in_minutes(curr_date, from_date), common.date_diff_in_minutes(next_date, from_date), color=my_colors[mode_set[m]], alpha=0.5)
        plt.show()
    
    #
    #    # CREATE FIGURE    
    #    if len(speed_data) > 0:
    #        fig, axarr = plt.subplots(ncols=2, figsize=(10,10))
    #        ax = axarr[0] 
    #    else:
    #        fig, axarr = plt.subplots(1, figsize=figsize)
    #        ax = axarr[0]
    #     
    #    # PLOT MATRIX
    #    res = ax.  
    ##    fig.colorbar(res)
    #    
    #    # XAXIS
    #    ax.set_xticklabels([], [])
    #    
    #    # YAXIS
    #    ax.set_ylabel('Access points')
    #    ax.set_ylim([0, len(vd)])
    #    
    #    if y_ticks:
    #        plt.yticks(xrange(0, len(router_names)), [item[1] for item in router_names])
    #        plt.tick_params(axis='y', which='major', labelsize=6)
    #    else:
    #        plt.setp(ax.get_yticklabels(), visible=False)
    #        plt.tick_params(axis='y', which='both', bottom='off', top='off', labelbottom='off')
    #        plt.yticks([], [])
    #    
    #    ax_size = get_ax_size(fig, ax)
    #    print ax_size
    #    # PLOT SPEED DATA
    #    if len(speed_data) > 0:
    #        ax.set_aspect(1)
    #        ax = axarr[1]
    #        ax.plot(speed_data.keys(), speed_data.values(), c = speed_color)
    #        ax.set_ylabel('Speed [km / h]')
    #        
    #        ax.set_xlabel("Time")
    #        ax.xaxis.set_major_formatter(mpld.DateFormatter('%d/%m/%y %H:%M'))
    #        for tick in ax.xaxis.get_major_ticks():
    #            tick.label.set_rotation('vertical')
    #            
    #        ax_size = get_ax_size(fig, ax)
    #        print ax_size
    ##        ax.set_xlim(from_date, end_date) 
    ##        ax.set_xticklabels(xrangeprepare_x_ticks(from_date, end_date, 24), rotation = 90)
    ##        
    ##    else:
    ##        plt.xlabel("Time")
    ##        tick_num = int((end_date - from_date).seconds / float(60))
    ##        plt.xticks(xrange(tick_num), prepare_x_ticks_words(from_date, end_date, tick_num), rotation=90)
    #        
        # SAVE
        axes[0].xaxis.grid()
        axes[1].yaxis.grid()
        plt.grid()
        plt.savefig(OUTPUT_FOLDER + "//" + figname, bbox_inches='tight')       
        plt.close(fig)
      
def append_to_file(data):
    with open("classification_features.txt", "a") as myfile:
        for idx in xrange(len(data) - 1):
            myfile.write(str(data[idx]))
            myfile.write('\t')
        myfile.write(str(data[-1]))
        myfile.write('\n')

def plot_speed(data, from_date, end_date, figname, figsize):
    fig, axarr = plt.subplots(1, figsize=figsize)
    ax = axarr
     
    # PLOT SPEED DATA
    plt.plot(data.keys(), data.values(), c = my_colors[0])
    
    # XAXIS
    plt.xlabel("Time")
    ax.xaxis.set_major_formatter(mpld.DateFormatter('%d/%m/%y %H:%M'))
    plt.tick_params(axis='x', which='major', labelsize=6)
    plt.xlim(from_date, end_date) 
    plt.xticks(prepare_x_ticks(from_date, end_date, 24), rotation=90)
    
    # YAXIS
    ax.set_ylabel('Speed [km / h]')
        
    # SAVE
    plt.savefig(OUTPUT_FOLDER + "//" + figname, bbox_inches='tight')       
    plt.close(fig)
    
def plot_new_router_slope(data, class_data_detail, from_date, end_date, figname, figsize):
    fig, axarr = plt.subplots(1, figsize=figsize)
    ax = axarr
     
    print data
    # PLOT SPEED DATA
    plt.plot(data.keys(), data.values(), c = my_colors[0])
    
    # XAXIS
    plt.xlabel("Time")
    ax.xaxis.set_major_formatter(mpld.DateFormatter('%d/%m/%y %H:%M'))
    plt.tick_params(axis='x', which='major', labelsize=6)
    plt.xlim(from_date, end_date) 
    plt.xticks(prepare_x_ticks(from_date, end_date, 24), rotation=90)
    
    # YAXIS
    ax.set_ylabel('Number of new routers')
        
    small_class_data_detail = OrderedDict()
    prev_date = None
    for idx in xrange(len(class_data_detail.keys())):
        curr_date = class_data_detail.keys()[idx]
        if curr_date >= from_date and curr_date <= end_date:
            if prev_date != None:
                small_class_data_detail[prev_date] = class_data_detail[prev_date] 
            small_class_data_detail[curr_date] = class_data_detail[curr_date]           
        prev_date = curr_date
    
    for idx in xrange(len(small_class_data_detail.keys())):
        curr_date = small_class_data_detail.keys()[idx]
        if idx == len(small_class_data_detail.keys()) - 1:
            next_date = end_date
        else:
            next_date = small_class_data_detail.keys()[idx + 1]
            
        mode = small_class_data_detail[curr_date]
        for m in mode_set:
            if m in mode:
                plt.axvspan(curr_date, next_date, color=my_colors[mode_set[m]], alpha=0.5)
                
    # SAVE
    plt.savefig(OUTPUT_FOLDER + "//" + figname, bbox_inches='tight')       
    plt.close(fig)